import BasePlugin from './BasePlugin';

/**
 * 键盘快捷键插件 - 处理键盘交互
 */
export default class KeyboardPlugin extends BasePlugin {
    constructor() {
        super();
        this.shortcuts = new Map();
        this.isCommandPressed = false;
        this.isShiftPressed = false;
        this.isAltPressed = false;
    }

    /**
     * 初始化插件
     */
    init(editor) {
        super.init(editor);
        this._setupDefaultShortcuts();
        this._setupEventListeners();
    }

    /**
     * 添加快捷键
     * @param {string} key - 键名
     * @param {Object} options - 快捷键配置
     * @param {Function} callback - 回调函数
     */
    addShortcut(key, options = {}, callback) {
        const shortcut = {
            key: key.toLowerCase(),
            ctrl: options.ctrl || false,
            shift: options.shift || false,
            alt: options.alt || false,
            callback
        };
        this.shortcuts.set(this._getShortcutKey(shortcut), shortcut);
    }

    /**
     * 移除快捷键
     */
    removeShortcut(key, options = {}) {
        const shortcutKey = this._getShortcutKey({
            key: key.toLowerCase(),
            ctrl: options.ctrl || false,
            shift: options.shift || false,
            alt: options.alt || false
        });
        this.shortcuts.delete(shortcutKey);
    }

    /**
     * 清除所有快捷键
     */
    clearShortcuts() {
        this.shortcuts.clear();
    }

    /**
     * 设置默认快捷键
     */
    _setupDefaultShortcuts() {
        // 复制
        this.addShortcut('c', { ctrl: true }, () => {
            this.editor.emit('copy');
        });

        // 粘贴
        this.addShortcut('v', { ctrl: true }, () => {
            this.editor.emit('paste');
        });

        // 剪切
        this.addShortcut('x', { ctrl: true }, () => {
            this.editor.emit('cut');
        });

        // 撤销
        this.addShortcut('z', { ctrl: true }, () => {
            this.editor.emit('undo');
        });

        // 重做
        this.addShortcut('z', { ctrl: true, shift: true }, () => {
            this.editor.emit('redo');
        });

        // 全选
        this.addShortcut('a', { ctrl: true }, () => {
            this.editor.emit('select:all');
        });

        // 删除
        this.addShortcut('delete', {}, () => {
            this.editor.emit('delete');
        });
        this.addShortcut('backspace', {}, () => {
            this.editor.emit('delete');
        });

        // 组合/取消组合
        this.addShortcut('g', { ctrl: true }, () => {
            this.editor.emit('group');
        });
        this.addShortcut('g', { ctrl: true, shift: true }, () => {
            this.editor.emit('ungroup');
        });

        // 锁定/解锁
        this.addShortcut('l', { ctrl: true }, () => {
            this.editor.emit('lock');
        });
        this.addShortcut('l', { ctrl: true, shift: true }, () => {
            this.editor.emit('unlock');
        });

        // 图层操作
        this.addShortcut(']', { ctrl: true }, () => {
            this.editor.emit('bring:forward');
        });
        this.addShortcut('[', { ctrl: true }, () => {
            this.editor.emit('send:backward');
        });
        this.addShortcut(']', { ctrl: true, shift: true }, () => {
            this.editor.emit('bring:to:front');
        });
        this.addShortcut('[', { ctrl: true, shift: true }, () => {
            this.editor.emit('send:to:back');
        });

        // 对齐操作
        this.addShortcut('h', { ctrl: true, shift: true }, () => {
            this.editor.emit('align:horizontal');
        });
        this.addShortcut('v', { ctrl: true, shift: true }, () => {
            this.editor.emit('align:vertical');
        });

        // 缩放操作
        this.addShortcut('0', { ctrl: true }, () => {
            this.editor.emit('zoom:reset');
        });
        this.addShortcut('+', { ctrl: true }, () => {
            this.editor.emit('zoom:in');
        });
        this.addShortcut('-', { ctrl: true }, () => {
            this.editor.emit('zoom:out');
        });
    }

    /**
     * 设置事件监听
     */
    _setupEventListeners() {
        if (!this.canvas) return;

        // 监听按键按下事件
        document.addEventListener('keydown', this._handleKeyDown.bind(this));
        document.addEventListener('keyup', this._handleKeyUp.bind(this));

        // 监听窗口失焦事件
        window.addEventListener('blur', this._handleWindowBlur.bind(this));
    }

    /**
     * 处理按键按下事件
     */
    _handleKeyDown(event) {
        if (!this.isEnabled()) return;

        // 更新修饰键状态
        if (event.key === 'Control' || event.key === 'Meta') {
            this.isCommandPressed = true;
        } else if (event.key === 'Shift') {
            this.isShiftPressed = true;
        } else if (event.key === 'Alt') {
            this.isAltPressed = true;
        }

        // 查找并执行快捷键
        const shortcut = this.shortcuts.get(
            this._getShortcutKey({
                key: event.key.toLowerCase(),
                ctrl: this.isCommandPressed,
                shift: this.isShiftPressed,
                alt: this.isAltPressed
            })
        );

        if (shortcut) {
            event.preventDefault();
            shortcut.callback();
        }
    }

    /**
     * 处理按键松开事件
     */
    _handleKeyUp(event) {
        if (event.key === 'Control' || event.key === 'Meta') {
            this.isCommandPressed = false;
        } else if (event.key === 'Shift') {
            this.isShiftPressed = false;
        } else if (event.key === 'Alt') {
            this.isAltPressed = false;
        }
    }

    /**
     * 处理窗口失焦事件
     */
    _handleWindowBlur() {
        this.isCommandPressed = false;
        this.isShiftPressed = false;
        this.isAltPressed = false;
    }

    /**
     * 生成快捷键标识
     */
    _getShortcutKey(shortcut) {
        return `${shortcut.ctrl ? 'ctrl+' : ''}${shortcut.shift ? 'shift+' : ''}${shortcut.alt ? 'alt+' : ''
            }${shortcut.key}`;
    }

    /**
     * 销毁插件
     */
    destroy() {
        if (this.canvas) {
            document.removeEventListener('keydown', this._handleKeyDown);
            document.removeEventListener('keyup', this._handleKeyUp);
            window.removeEventListener('blur', this._handleWindowBlur);
            this.shortcuts.clear();
        }
        super.destroy();
    }
} 